package com.cpimex.eprice.action;

import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;

import javax.naming.InitialContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;
import org.apache.struts.upload.FormFile;

import com.cpimex.eprice.action.plugin.ConnectionBuilder;
import com.cpimex.eprice.forms.PriceUploadForm;
import com.cpimex.eprice.model.PriceTool;


/**
 * 
 * 
 *
 */
public class PriceUploadAction extends MappingDispatchAction {

	private final String DEFAULT = "default";
	
	
	/**
	 * Subida de Precios 
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward upload(
			ActionMapping mapping, 
			ActionForm form, 
			HttpServletRequest request, 
			HttpServletResponse response) throws Exception {
		
		InitialContext context = new InitialContext();
		//DataSource dataSrc = (DataSource) context.lookup("java:comp/env/jdbc/Eprice");
		//Connection conn = ConnectionBuilder.epriceConnection(context);
		DataSource dataSrc = (DataSource) context.lookup("java:comp/env/jdbc/Eprice");
		Connection conn = dataSrc.getConnection();
		
				
		PriceUploadForm forma  = (PriceUploadForm) form;
		FormFile file   = forma.getFile_precios();
		String str_name = file.getFileName();
		
		byte[] byte_archivo = file.getFileData();
		
		
		ServletContext sc  =  getServlet().getServletContext();
		String str_filePath = sc.getRealPath("/");
		str_filePath += "archivo\\";
		
		File f = new File(str_filePath+"\\"+str_name);
		try{
			FileOutputStream ostr_file = new FileOutputStream(f);
			
			ostr_file.write(byte_archivo);
			ostr_file.close();
			
			PriceTool pt = new PriceTool(conn, f);
			String str_log = pt.upload();
			
			
			request.setAttribute("path", str_log);
			return mapping.findForward(DEFAULT);
		}catch(Exception e){
			throw e;
		}finally{
			f.delete();
			conn.close();
		}
	}
	
}
